<template>
	<view class="content">
		<view class="m10">
			<uni-easyinput @iconClick="getNewOnlineUser(1,true)" type="text" v-model="visitor_name"  placeholder="搜索访客名称" suffixIcon="search"/>
			<uni-data-picker class="mt-10" :localdata="entTags" popup-title="请选择标签" @change="changeTag"></uni-data-picker>
		</view>
		<view class="m10">
		    <uni-list :border="true">
		        <uni-list-chat clickable @click="chatVisitor($event,item.visitor_id)" :title="item.username" v-for="item in visitors" :avatar="item.avator" :note="showLastMessage(item.last_message)" :time="formatTime(item.updated_at)" badge-positon="left" :badge-text="item.unread_num"></uni-list-chat>
		    </uni-list>
			
		</view>
		<uni-pagination class="m10 mb20" :total="total" :pageSize="pageSize"  @change="changePage"/>
		<view class="flyNotice" v-show="visitors.length==0">
			<uni-icons class="mr-10" type="chatboxes" color="#808080" size="30"></uni-icons>
			暂无在线访客
		</view>
	</view>

</template>

<script>
	import toolsHelper from '../../common/tools.js';
	import visitorHelper from '../../common/visitors.js';
	export default {
		data() {
			return {
				title: 'Hello',
				baseUrl: getApp().globalData.baseUrl,
				wsBaseUrl: getApp().globalData.wsBaseUrl,
				visitors: [],
				token: "",
				timer: null,
				wsOpen: false,
				noticeContent:"通知: 无",
	
				            avatarList: [{
				                url: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/460d46d0-4fcc-11eb-8ff1-d5dcf8779628.png'
				            }, {
				                url: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/460d46d0-4fcc-11eb-8ff1-d5dcf8779628.png'
				            }, {
				                url: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/460d46d0-4fcc-11eb-8ff1-d5dcf8779628.png'
				            }],
				visitor_name:"",
				entTags:[],
				visitorTag:null,
				page: 1,
				total: 0,
				pageSize: 10
			}
		},
		// 页面显示
		onShow() {
			let _this = this;
			let res = uni.getStorageSync('app');
			if (res) {
				this.token = res.token;
			}
			let domainInfo = uni.getStorageSync('domain');
			if (domainInfo) {
				this.baseUrl = domainInfo.domain;
				this.wsBaseUrl=toolsHelper.getWsUrl(domainInfo.domain);
			}
			//_this.page=1;
			this.checkAuth();
			this.getNewOnlineUser(_this.page,true);
			this.getTags();
		},
		onLoad() {
		},
		onPullDownRefresh(){
			console.log('refresh');
			this.getNewOnlineUser(1,true)
			setTimeout(function () {
				uni.stopPullDownRefresh();
			}, 1000);
		},

		// onReachBottom(){
		// 	console.log(this.page);
		// 	++this.page;
		// 	this.getNewOnlineUser(this.page,false)
		// },
		methods: {
			//用户实时上下线
			onlineIntime() {
				var _this = this;
				var timer = null;
				uni.connectSocket({
					url: this.wsBaseUrl + "?token=" + this.token,
				});
				uni.onSocketClose((res) => {
					clearInterval(timer);
					console.log("WebSocket 连接断开");
				});
				uni.onSocketOpen((res) => {
					console.log("WebSocket 连接已打开");;
					let _this = this;
					let mes = {}
					mes.type = "ping";
					mes.data = "";
					timer = setInterval(function() {
						uni.sendSocketMessage({
							data: JSON.stringify(mes),
						});
					}, 5000)

				});
				uni.onSocketMessage((res) => {
					var redata = JSON.parse(res.data);
					switch (redata.type) {
						case "userOnline":
							toolsHelper.playVoice();
							_this.showNoticeBar(redata.data.username+"来了");
							break;
						case "userOffline":
							_this.showNoticeBar(redata.data.name+"离线");
							break;
						case "message":
							this.recvMessage(redata.data);
							break;
					}
				});
			},
			recvMessage(msg) {
				this.visitors = visitorHelper.receiveMessage(this.visitors,msg);
				this.showNoticeBar(msg.name+":"+ msg.content);
				if(msg.is_kefu != "yes"){
					toolsHelper.playVoice();
				}
			},
			getOnlineUser(page) {
				let _this = this;
				var baseUrl = this.baseUrl;
				uni.request({
					url: baseUrl + '/visitors?page='+page+'&pagesize=14&token=' + _this.token,
					method: 'GET',
					success: function(res) {
						console.log(res);
						if (!res.data.result.list) {
							return;
						}
						var list=res.data.result.list
						for(var i=0;i<list.length;i++){
							list[i].avator=toolsHelper.getImageUrl(list[i].avator,_this.baseUrl);
						}
						if(_this.visitors.length==0){
							_this.visitors=list;
						}else{
							_this.visitors=_this.visitors.concat(_this.visitors,list);
						}
						_this.visitors=_this.removeRepeat(_this.visitors);
					},
					fail: function(res) {}
				});
			},
			getNewOnlineUser(page,newList) {
				let _this = this;
				var baseUrl = this.baseUrl;
				var params={
					page:page,
					pagesize:15,
					token: _this.token,
					kefuName:"",
					visitorName:_this.visitor_name,
					visitorTag:_this.visitorTag,
				};
				uni.request({
					url: baseUrl + '/kefu/visitorList',
					method: 'GET',
					data:params,
					success: function(res) {
						if (!res.data.result.list) {
							return;
						}
						_this.total=res.data.result.count;
						_this.pageSize=res.data.result.pagesize;
						if(newList){
							_this.visitors=[];
						}
						var list=res.data.result.list;
						for(var i=0;i<list.length;i++){
							list[i].avator=toolsHelper.getImageUrl(list[i].avator,_this.baseUrl);
						}
						
						if(_this.visitors.length==0){
							_this.visitors=list;
						}else{
							_this.visitors=_this.visitors.concat(_this.visitors,list);
						}
						_this.visitors=_this.removeRepeat(_this.visitors);
					},
				});
			},
			changePage(e){
				if(e.type="next"){
					this.page++;
				}
				if(e.type="prev"){
					this.page--;
				}
				if(e.type="current"){
					this.page=e.current;
				}
				this.getNewOnlineUser(this.page,true);
			},
			//点击
			chatVisitor(e, visitorId) {
				uni.navigateTo({
					url: '/pages/index/detail?visitor_id=' + visitorId
				})
			},
			showNoticeBar(msg){
				var _this=this;
				_this.noticeContent=msg;
			},
			checkAuth() {
				var _this = this;
				uni.request({
					url: _this.baseUrl + '/uc/v1/refreshToken?token=' + _this.token,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						var code = res.data.code;
						if (code != 20000) {
							uni.navigateTo({
								url: '/pages/index/login'
							});
						} else {
							uni.setStorageSync("app", {
								token: res.data.result.token,
							});
							_this.onlineIntime();
						}
					}
				});
			},
			removeRepeat(arr){
				var i = 0,
					j = arr.length,
					cache = {},
					key, result = [];
				for (; i < j; i++) {
					key = arr[i].id;
					key = typeof(key) + key;
					if (!cache[key]) {
						cache[key] = 1;
						result.push(arr[i]);
					}
				}
				return result;

			},
			showLastMessage(mes){
				if(mes==""){
					return "无消息";
				}
				return mes
			},
			formatTime(time, fmt) {
				var time = Math.round(new Date(time).getTime()/1000);
				return toolsHelper.beautifyTime(time)
			},
			//查询tags
			getTags(){
				var _this=this;
				_this.entTags=[];
				_this.visitorTag=null;
				uni.request({
					url: this.baseUrl + '/kefu/tags?token='+_this.token,
					method: 'GET',
					success: function(res) {
						var result=res.data.result;
						for(var key in result){
							var item={
								"text":result[key].name,
								"value":result[key].id,
							}
							_this.entTags.push(item);
						}
					}
				});
			},
			//修改标签
			changeTag(e){
				var _this=this;
				var value=null;
				if(e.detail.value[0]){
					 value= e.detail.value[0].value;
				}
		
				this.visitorTag=value;
				this.getNewOnlineUser(1,true)
				
			},
		}
	}
</script>

<style>
.content{
	padding: 0px 2px;
}
</style>
